package manage

import (
	"lingc/models"
	"lingc/services"
	"lingc/utils" // 导入 common 包
	"strings"

	"github.com/gin-gonic/gin"
)

// PageUser 获取所有用户
func PageMemberLevel(c *gin.Context) {

	var dataRequest struct {
		Keywords string `json:"keywords" form:"keywords"`
		LevelID  string `json:"level_id" form:"level_id"`
		Status   string `json:"status" form:"status"`
		Page     int    `json:"page" form:"page"`
		PageSize int    `json:"pageSize" form:"pageSize"` // Exported field
	}
	// Bind query parameters to dataRequest
	if err := c.ShouldBind(&dataRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request parameters"})
		return
	}
	where := ""
	if dataRequest.Keywords != "" {
		keyword := "'%" + dataRequest.Keywords + "%'"
		where += " (`username` like " + keyword + " or `phone` like " + keyword + " or `email` like" + keyword + ")"
	}
	if dataRequest.LevelID != "" {
		if where != "" {
			where += " and "
		}
		where += " level_id = " + dataRequest.LevelID
	}
	if dataRequest.Status != "" {
		if where != "" {
			where += " and "
		}
		where += " status = " + dataRequest.Status
	}
	// log.Printf("PageUserWhere: %s", where)
	list, page, total, err := services.NewMemberLevelService(utils.MysqlClient).PageMemberLevelList(where, dataRequest.Page, dataRequest.PageSize)
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"list": list, "page": page, "total": total})
}

// GetUser 获取用户
func GetMemberLevel(c *gin.Context) {

	var dataRequest struct {
		Keyword string `json:"keyword" form:"keyword"`
		Status  string `json:"status" form:"status"`
	}

	where := ""
	if err := c.ShouldBind(&dataRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	if dataRequest.Keyword != "" {
		keyword := "%" + dataRequest.Keyword + "%"
		where += " (username like " + keyword + " or realname like " + keyword + ")"
	}
	if dataRequest.Status != "" {
		if where != "" {
			where += " and "
		}
		where += " status = " + dataRequest.Status
	}

	user, err := services.NewMemberLevelService(utils.MysqlClient).GetMemberLevel(where)
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"data": user})
}

// CreateUser 创建用户
func CreateMemberLevel(c *gin.Context) {

	/*
		LevelID   uint    `json:"level_id"`
		LevelName string  `json:"level_name"`
		Src       string  `json:"src"`
		Money     float64 `json:"money"`
		Duration  int64   `json:"duration"`
		AppID     int     `json:"app_id"`
	*/
	var createRequest struct {
		LevelID   uint   `json:"level_id" form:"level_id"`
		LeveLName string `json:"level_name" form:"level_name"`
		Src       string `json:"src" form:"src"`
		Money     string `json:"money" form:"money"`
		Duration  int64  `json:"duration" form:"duration"`
	}
	if err := c.ShouldBindJSON(&createRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	moneyFloat := utils.ParseFloat(createRequest.Money)
	user := &models.MemberLevelCreate{
		LevelID:   createRequest.LevelID,
		LevelName: createRequest.LeveLName,
		Money:     moneyFloat,
		Src:       createRequest.Src,
		Duration:  createRequest.Duration,
	}
	// log.Printf("CreateMemberLevel: %v", user)
	data, err := services.NewMemberLevelService(utils.MysqlClient).CreateMemberLevel(user)
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"data": data})
}

// UpdateUser 更新用户
func UpdateMemberLevel(c *gin.Context) {
	var createRequest struct {
		ID        uint   `json:"id" form:"id"`
		LevelID   uint   `json:"level_id" form:"level_id"`
		LeveLName string `json:"level_name" form:"level_name"`
		Src       string `json:"src" form:"src"`
		Money     string `json:"money" form:"money"`
		Duration  int64  `json:"duration" form:"duration"`
	}
	if err := c.ShouldBindJSON(&createRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "update Invalid request parameters"})
		return
	}
	moneyFloat := utils.ParseFloat(createRequest.Money)
	user := &models.MemberLevelUpdate{
		ID:        createRequest.ID,
		LevelID:   createRequest.LevelID,
		LevelName: createRequest.LeveLName,
		Src:       createRequest.Src,
		Money:     moneyFloat,
		Duration:  createRequest.Duration,
	}
	data, err := services.NewMemberLevelService(utils.MysqlClient).UpdateMemberLevel(user)
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"data": data})
}

// DeleteUser 删除用户
func DeleteMemberLevel(c *gin.Context) {
	var createRequest struct {
		ID  uint   `json:"id" form:"id"`
		IDs string `json:"ids" form:"ids"`
	}
	if err := c.ShouldBind(&createRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	// log.Printf("DeleteMemberLevel: %v", createRequest)

	if createRequest.ID == 0 && len(createRequest.IDs) == 0 {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	if createRequest.ID != 0 {
		if err := services.NewMemberLevelService(utils.MysqlClient).DeleteMemberLevel(createRequest.ID); err != nil {
			utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
			return
		}
	}

	if len(createRequest.IDs) == 0 {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	idStrs := strings.Split(createRequest.IDs, ",")
	var ids []string
	for _, idStr := range idStrs {
		idStr = strings.TrimSpace(idStr)
		if idStr == "" {
			continue
		}
		ids = append(ids, idStr)
	}
	// Convert IDs slice to a format suitable for batch deletion
	if len(ids) == 0 {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "No valid IDs provided"})
		return
	}
	if err := services.NewMemberLevelService(utils.MysqlClient).DeleteMemberLevels(ids); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	// ... 这里添加删除用户的逻辑 ...
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"msg": "Delete user"})
}
